package org.gcoat.list;

import java.util.Arrays;

public class ArrayIntList implements IntList {
	private static final int INITIAL_CAPACITY = 32;
	private int size_;
	private int[] array_;

	public ArrayIntList() {
		this(INITIAL_CAPACITY);
	}

	public ArrayIntList(int initialCapacity) {
		array_ = new int[initialCapacity];
		size_ = 0;
	}

	void rangeCheck(int index) {
		if (index < 0 || index >= size_) {
			throw new IndexOutOfBoundsException("index = " + index + "; size = " + size_);
		}
	}

	@Override
	public int size() {
		return size_;
	}

	@Override
	public int get(int index) {
		rangeCheck(index);
		return array_[index];
	}

	@Override
	public int set(int index, int value) {
		rangeCheck(index);
		int res = array_[index];
		array_[index] = value;
		return res;
	}

	@Override
	public void add(int value) {
		if (array_.length == size_) {
			int len = array_.length;
			array_ = Arrays.copyOf(array_, len + (len >> 1) + 1);
		}
		array_[size_] = value;
		++size_;
	}

	@Override
	public void clear() {
		size_ = 0;
	}

	public void trimToSize() {
		if (array_.length != size_) {
			array_ = Arrays.copyOf(array_, size_);
		}
	}
}
